package mqtt

import (
	"encoding/json"
	pmqtt "github.com/eclipse/paho.mqtt.golang"
	"shangke-device/internal/mqtt"
)

var Subscribes = []mqtt.Subscribe{
	{
		Topic: "device/response", //订阅设备响应结果主题
		Qos:   2,
		Handler: func(s *mqtt.Server) pmqtt.MessageHandler {
			return func(c pmqtt.Client, message pmqtt.Message) {
				request := &mqtt.DeviceReplyRequest{
					Request: mqtt.Request{
						Topic:    message.Topic(),
						Qos:      message.Qos(),
						Retained: message.Retained(),
					},
				}
				err := json.Unmarshal(message.Payload(), &request.Payload)
				if err != nil {
					s.Log.Error().Msgf("Subscribe: topic[%s] retained[%t] Payload[%s] err: %s \r\n", message.Topic(), message.Retained(), message.Payload(), err)
					return
				}

				s.Log.Debug().Msgf("Subscribe: topic[%s] retained[%t] Payload[%s] success... \r\n", message.Topic(), message.Retained(), message.Payload())
				s.GetClient(request.Payload.ClientId).WriteReply(request.Payload.MsgID, request.Payload.Data)
			}
		},
	},
}
